package com.spring.demo.security;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

/**
 * 想登录页跳转的控制，根据被请求所需权限不同向不同的登录页跳转
 * @author ld2016
 *
 */
//@Component("myAuthenticationEntryPoint")
public class MyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

	public MyAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
		System.out.println(loginFormUrl);
		// TODO Auto-generated constructor stub
	}

	private Map<String,String> authEntryPointMap;
	private PathMatcher pathMatcher = new AntPathMatcher();
	
	@Override
	protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) {
		// TODO Auto-generated method stub
		authEntryPointMap = new HashMap<String, String>();  //设置不同请求返回不同的登录页面
		authEntryPointMap.put("/admin/**", "/user/login");
		authEntryPointMap.put("/user/**", "/user/login");
		authEntryPointMap.put("/**", "/user/login");
		String requestURI = request.getRequestURI().replace(request.getContextPath(), "");
		for (String url : this.authEntryPointMap.keySet()) {
			if(this.pathMatcher.match(url, requestURI)) {
				return this.authEntryPointMap.get(url);
			}
		}
		return super.determineUrlToUseForThisRequest(request, response, exception);
	}
}
